<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>PDF中文水印</title>
    <style>
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            margin: 30px auto;
            max-width: 1200px;
            background-color: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
        }
        .input-group {
            display: flex;
            gap: 10px;
            margin-bottom: 20px;
        }
        input[type="file"],
        input[type="text"] {
            padding: 10px;
            border: 1px solid #ccc;
            border-radius: 4px;
            box-sizing: border-box;
            flex: 1;
        }
        button {
            padding: 10px 20px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            transition: background-color 0.3s ease;
        }
        #addWatermark {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
        }
        #addWatermark:hover {
            background: linear-gradient(135deg, #5a6ecf 0%, #683d91 100%);
        }
        #cancel {
            background-color: #999;
            color: white;
        }
        #cancel:hover {
            background-color: #777;
        }
        #downloadImages {
            background: linear-gradient(135deg, #999999 0%, #7454af 100%);
            color: white;
            text-shadow: 0 1px 2px rgba(0, 0, 0, 0.2);
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
        }
        #downloadImages:hover {
            background: linear-gradient(135deg, #22923d 0%, #1d7831 100%);
            box-shadow: 0 6px 8px rgba(0, 0, 0, 0.15);
        }
        .preview-group {
            display: flex;
            gap: 20px;
        }
        .preview-group > div {
            flex: 1;
        }
        .preview-group h2 {
            margin-top: 0;
            color: #333;
        }
        .preview-group .canvas-container {
            overflow-y: auto;
            height: 500px;
            border: 1px solid #ccc;
            border-radius: 4px;
            padding: 10px;
        }
        .preview-group canvas {
            width: 100%;
            border: 1px solid #ccc;
            background-color: white;
            border-radius: 4px;
            margin-bottom: 10px;
        }
    </style>
</head>
<body>
    <div class="input-group">
        <input type="file" id="pdfInput" accept=".pdf">
        <input type="text" id="watermarkText" placeholder="输入水印文字">
        <button id="addWatermark">添加水印</button>
        <button id="cancel">取消</button>
        <button id="downloadImages">批量下载图片</button>
    </div>
    <div class="preview-group">
        <div>
            <h2>文件预览</h2>
            <div class="canvas-container" id="originalPdfContainer"></div>
        </div>
        <div>
            <h2>水印预览</h2>
            <div class="canvas-container" id="watermarkedPdfContainer"></div>
        </div>
    </div>
    <script src="../js/pdf.min.js"></script>
    <script>
        const pdfInput = document.getElementById('pdfInput');
        const watermarkText = document.getElementById('watermarkText');
        const addWatermarkBtn = document.getElementById('addWatermark');
        const cancelBtn = document.getElementById('cancel');
        const downloadImagesBtn = document.getElementById('downloadImages');
        const originalPdfContainer = document.getElementById('originalPdfContainer');
        const watermarkedPdfContainer = document.getElementById('watermarkedPdfContainer');
        pdfInput.addEventListener('change', async (e) => {
            const file = e.target.files[0];
            if (file) {
                const reader = new FileReader();
                reader.onload = async (event) => {
                    const arrayBuffer = event.target.result;
                    const loadingTask = pdfjsLib.getDocument({ data: arrayBuffer });
                    const pdf = await loadingTask.promise;
                    const numPages = pdf.numPages;
                    originalPdfContainer.innerHTML = '';
                    const scaleFactor = 2;
                    for (let pageNumber = 1; pageNumber <= numPages; pageNumber++) {
                        const page = await pdf.getPage(pageNumber);
                        const viewport = page.getViewport({ scale: 1.0 });
                        const canvas = document.createElement('canvas');
                        canvas.height = viewport.height * scaleFactor;
                        canvas.width = viewport.width * scaleFactor;
                        canvas.style.height = viewport.height + 'px';
                        canvas.style.width = viewport.width + 'px';
                        const ctx = canvas.getContext('2d');
                        ctx.scale(scaleFactor, scaleFactor);
                        await page.render({
                            canvasContext: ctx,
                            viewport: viewport
                        }).promise;
                        originalPdfContainer.appendChild(canvas);
                    }
                };
                reader.readAsArrayBuffer(file);
            }
        });
        addWatermarkBtn.addEventListener('click', async () => {
            const file = pdfInput.files[0];
            const text = watermarkText.value;
            if (file && text) {
                const reader = new FileReader();
                reader.onload = async (event) => {
                    const arrayBuffer = event.target.result;
                    const loadingTask = pdfjsLib.getDocument({ data: arrayBuffer });
                    const pdf = await loadingTask.promise;
                    const numPages = pdf.numPages;
                    watermarkedPdfContainer.innerHTML = '';
                    const watermarkedCanvases = [];
                    const scaleFactor = 2;
                    for (let pageNumber = 1; pageNumber <= numPages; pageNumber++) {
                        const page = await pdf.getPage(pageNumber);
                        const viewport = page.getViewport({ scale: 1.0 });
                        const canvas = document.createElement('canvas');
                        canvas.height = viewport.height * scaleFactor;
                        canvas.width = viewport.width * scaleFactor;
                        canvas.style.height = viewport.height + 'px';
                        canvas.style.width = viewport.width + 'px';
                        const ctx = canvas.getContext('2d');
                        ctx.scale(scaleFactor, scaleFactor);
                        await page.render({
                            canvasContext: ctx,
                            viewport: viewport
                        }).promise;
                        ctx.save();
                        ctx.globalAlpha = 0.3;
                        ctx.fillStyle = 'gray';
                        ctx.translate(viewport.width / 2, viewport.height / 2);
                        ctx.rotate(-45 * Math.PI / 180);
                        let fontSize = 100;
                        ctx.font = `${fontSize}px Arial`;
                        let textWidth = ctx.measureText(text).width;
                        while (textWidth > viewport.width * 0.8 || textWidth > viewport.height * 0.8) {
                            fontSize -= 5;
                            ctx.font = `${fontSize}px Arial`;
                            textWidth = ctx.measureText(text).width;
                        }
                        const textMetrics = ctx.measureText(text);
                        const textX = -textMetrics.width / 2;
                        const textY = textMetrics.actualBoundingBoxAscent / 2 - textMetrics.actualBoundingBoxDescent / 2;
                        ctx.fillText(text, textX, textY);
                        ctx.restore();
                        watermarkedCanvases.push(canvas);
                        watermarkedPdfContainer.appendChild(canvas);
                    }
                };
                reader.readAsArrayBuffer(file);
            }
        });
        downloadImagesBtn.addEventListener('click', () => {
            const watermarkedCanvases = Array.from(watermarkedPdfContainer.querySelectorAll('canvas'));
            if (watermarkedCanvases.length === 0) {
                alert('没有可下载的图片，请先添加水印。');
                return;
            }
            let imageIndex = 1;
            watermarkedCanvases.forEach((canvas) => {
                try {
                    const imgData = canvas.toDataURL('image/png');
                    const a = document.createElement('a');
                    a.href = imgData;
                    a.download = `page_${imageIndex}.png`;
                    a.click();
                    imageIndex++;
                } catch (error) {
                    console.error(`下载第 ${imageIndex} 张图片时出错:`, error);
                    alert(`下载第 ${imageIndex} 张图片时出错，请检查控制台日志。`);
                }
            });
        });
        cancelBtn.addEventListener('click', () => {
            pdfInput.value = '';
            watermarkText.value = '';
            originalPdfContainer.innerHTML = '';
            watermarkedPdfContainer.innerHTML = '';
        });
    </script>
</body>
</html>
    